package com.yaodian100.ec.order.web;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.commons.betwixt.io.BeanWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;

import com.opensymphony.xwork2.ActionSupport;
import com.yaodian100.core.batch.service.BatchJobService;
import com.yaodian100.core.common.dao.impl.CommonCriteria;
import com.yaodian100.core.common.service.BaseManager;
import com.yaodian100.core.common.utils.StringUtils;
import com.yaodian100.ec.order.entity.Orders;
import com.yaodian100.ec.order.entity.ServiceOrderDetail;
import com.yaodian100.ec.order.entity.ServiceOrderProduct;
import com.yaodian100.ec.order.entity.ServiceOrders;
import com.yaodian100.ec.order.remote.ODetail;
import com.yaodian100.ec.order.remote.ServiceOrderBo;
import com.yaodian100.ec.order.remote.ServiceProduct;
import com.yaodian100.ec.order.service.OrderService;
import com.yaodian100.ec.order.service.ServiceOrderService;
import com.yaodian100.ec.payment.entity.BankTransfer;
import com.yaodian100.ec.payment.entity.ThirdPartyTransfer;
import com.yaodian100.ec.payment.service.TransferService;

/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 Module Name          : .CommonTest
 Module Description   :

 Date Created      : 2011/12/12
 Original Author   : feeling.wang
 Team              : yaodian100
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 MODIFICATION HISTORY
 ------------------------------------------------------------------------------
 Date Modified       Modified by       Comments
 ------------------------------------------------------------------------------
 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/

/**
 * @author feeling.wang
 * 
 */
public class CommonTestAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private final Logger logger = LoggerFactory.getLogger(CommonTestAction.class);
	@Autowired
	private OrderService orderService;
	@Autowired
	private TransferService transferService;
	@Autowired
	private JdbcTemplate jdbcTemplate;
	@Autowired
	private BaseManager baseMgr;
	@Autowired
	private ServiceOrderService serviceOrderService;
	@Autowired
	private BatchJobService batchJobService;
	private String orderId;
	private String serviceId;
	private String result;

	/**
	 * 收款并同步至后台(部份取消用)
	 * 
	 * @return
	 */
	public String deliveryOrderProcess() {
		if (StringUtils.isBlank(orderId)) {
			result = "订单编号不得为空值";
		} else {
			try {
				Orders order = orderService.get(orderId);
				if (null == order) {
					result = "查无订单编号：" + orderId + "资料";
				} else {
					if (order.getCash().compareTo(BigDecimal.ZERO) != 0) {
						result = "订单编号：" + orderId + "已收款,请勿重覆执行收款动作";
					} else {
						chargeOrder(order);
						// 同步订单至后台
						syncOrder(order);
						result = "订单编号：" + orderId + ",收款成功并同步至后台";
					}
				}
			} catch (Exception e) {
				result = "订单编号：" + orderId + ",收款失败";
				logger.info("exception:{}", e.toString());
			}
		}
		return "deliveryOrderProcessJson";
	}

	/**
	 * 收款
	 * 
	 * @return
	 */
	public String chargeOrder() {
		if (StringUtils.isBlank(orderId)) {
			result = "订单编号不得为空值";
		} else {
			try {
				Orders order = orderService.get(orderId);
				if (null == order) {
					result = "查无订单编号：" + orderId + "资料";
				} else {
					// if (order.getMustPay().compareTo(BigDecimal.ZERO) == 1 && order.getCash().compareTo(BigDecimal.ZERO) != 0)
					// {
					// result = "订单编号：" + orderId + "已收款,请勿重覆执行收款动作";
					// } else {
					String[] orderIds = order.getJoinOrders().split(",");
					if (order.getMustPay().compareTo(BigDecimal.ZERO) == 1) {
						chargeOrder(order);
					}

					// 執行商品已送達並同步至後台
					for (String oId : orderIds) {
						deliveryOrder(oId);
					}
					result = "订单编号：" + orderId + ",收款成功";
					// }
				}
			} catch (Exception e) {
				result = "订单编号：" + orderId + ",收款失败";
				logger.info("exception:{}", e.toString());
			}
		}
		return "chargeJson";
	}

	Orders chargeOrder(Orders order) {
		logger.info("order.getOrderSt():{}", order.getOrderSt());
		// 未付款才可做收款動作
		String tid = "123456";
		String src = "01";
		String bankCode = "";
		if ("10".equals(order.getOrderSt())) {
			// 銀行匯款(10)，郵局匯款(20)
			if (Arrays.asList("10", "20").contains(order.getPaymentTp())) {
				BankTransfer bank = new BankTransfer();
				bank.setOrderId(orderId);
				bank.setAmount(order.getJoinMustPay());
				bank.setBankMemo("");
				bank.setBillDate(new Date());
				bank.setDataEntryDate(new Date());
				bank.setDataEntryMan("feeling.wang");
				bank.setSourceAccountName("feelilng");
				bank.setSourceAccountNo("123456789");
				bank.setSourceBank("中国招商银行");
				bank.setStatus("10");
				bank.setSourceRemit("POST");
				transferService.saveBankTransfer(bank);
				orderService.charge(orderId, bank.getId(), order.getJoinMustPay());
			} else if (Arrays.asList("50", "70", "80").contains(order.getPaymentTp())) {// 網上支付(50)，信用卡單期(70)，信用卡分期(80)
				ThirdPartyTransfer thirdpartyTransfer = new ThirdPartyTransfer();
				thirdpartyTransfer.setOrderId(orderId);
				thirdpartyTransfer.setResult("0000");// 交易成功与否
				thirdpartyTransfer.setSrc(src);
				thirdpartyTransfer.setStatus("10");// 交易状态
				thirdpartyTransfer.setTid(tid);
				thirdpartyTransfer.setTradeEndDt(new Date());
				thirdpartyTransfer.setTradeStartDt(new Date());
				thirdpartyTransfer.setAmount(order.getJoinMustPay());
				thirdpartyTransfer.setBankCode(bankCode);
				thirdpartyTransfer = transferService.save(thirdpartyTransfer);
				// 第三方成功付款紀錄寫入和訂單是否寫入成功
				orderService.charge(orderId, thirdpartyTransfer.getId(), order.getJoinMustPay(), src);
			}
		}
		if ("35".contains(order.getOrderSt())) {
			if (Arrays.asList("30", "60").contains(order.getPaymentTp())) {// cod 現金(30)，pos(60)
				String[] orderIds = order.getJoinOrders().split(",");
				logger.info("orderIds:{}", orderIds.length);
				for (String oId : orderIds) {
					logger.info("xxx:{}", oId);
					if (!oId.equals(order.getOrderId())) {
						order = orderService.get(oId);
					}
					order.setCash(order.getMustPay());
					orderService.calcOrderCash(order);
					orderService.update(order);
				}
			}
		}
		return order;
	}

	/**
	 * 退货完成
	 * 
	 * @return
	 */
	public String returnProduct() {
		try {
			if (StringUtils.isBlank(serviceId)) {
				result = "退货单号不得为空值";
			} else {
				ServiceOrders so = serviceOrderService.get(serviceId);
				if (null == so) {
					result = "查无退货单号：" + serviceId + "资料";
				} else {
					if ("90".equals(so.getReturnSt())) {
						result = "已退货完成,请勿重覆退货";
					} else {
						ServiceOrders so1 = (ServiceOrders) baseMgr.get(ServiceOrders.class, serviceId);
						ServiceOrderBo sob = new ServiceOrderBo();
						sob.setId(so1.getServiceId());
						sob.setRealBenefit(so1.getRealBenefit().floatValue());
						sob.setRealBonus(so1.getRealBonus().floatValue());
						sob.setRealCash(so1.getRealCash().floatValue());
						sob.setRealGiftcardBalance(so1.getRealGiftcardBalance().floatValue());
						sob.setRealInstallmentFee(so1.getRealInstallmentFee().floatValue());
						sob.setRealMyWallet(so1.getRealMyWallet().floatValue());
						sob.setRealShipfare(so1.getRealShipfare().floatValue());
						sob.setReturnStatus("30");
						sob.setStatus(1);// 不知要写啥
						sob.setRefundApproveDate(new Date());
						sob.setRefundDate(new Date());

						CommonCriteria crit = new CommonCriteria();
						crit.addEq("serviceId", serviceId);
						List<ServiceOrderProduct> sops = serviceOrderService.getServiceOrderProdList(0, -1, crit, null);
						List<ServiceProduct> sopList = new ArrayList<ServiceProduct>();
						for (ServiceOrderProduct sop : sops) {
							ServiceProduct sp = new ServiceProduct();
							sp.setId(sop.getServiceProdId());
							sp.setLogisticCompany(sop.getLogisticCompany());
							sp.setLogisticFinalDt(sop.getLogisticFinalDt());
							sp.setLogisticRefNum(sop.getLogisticRefNum());
							sp.setLogisticRemark(sop.getLogisticRemark());
							sp.setLogisticSendDt(sop.getLogisticSendDt());
							sp.setLogisticSignDt(so1.getLogisticSignDt());
							sp.setLogisticSt(sop.getLogisticSt());
							List<ODetail> detail = new ArrayList<ODetail>();

							crit = new CommonCriteria();
							crit.addEq("serviceId", serviceId);
							crit.addEq("serviceProdId", sop.getServiceProdId());
							List<ServiceOrderDetail> sods = serviceOrderService.getServiceOrderDetailList(0, -1, crit, null);
							for (ServiceOrderDetail sod : sods) {
								ODetail od = new ODetail();
								od.setErpCost(sod.getErpCost());
								od.setOrderDetailId(sod.getOrderDetailId());
								od.setServiceDetailId(sod.getServiceDetailId().toString());
								od.setShippingLineOid("SP110315000000004");
								od.setShippingOid("15522");
								od.setVendId("000023");
								detail.add(od);
							}
							sp.setDetail(detail);
							sopList.add(sp);
						}
						sob.setServiceProducts(sopList);
						serviceOrderService.updateServiceOrderStatus(sob);
						result = "退货单号：" + serviceId + ",退货完成成功";
					}
				}
			}
		} catch (Exception e) {
			result = "退货单号：" + serviceId + ",退款失败";
			logger.info("exception:{}", e.toString());
		}
		return "returnJson";
	}

	/**
	 * 换货完成
	 * 
	 * @return
	 */
	public String changeProduct() {
		try {
			if (StringUtils.isBlank(serviceId)) {
				result = "换货单号不得为空值";
			} else {
				ServiceOrders so = serviceOrderService.get(serviceId);
				if (null == so) {
					result = "查无换货单号：" + serviceId + "资料";
				} else {
					if ("90".equals(so.getOrderSt())) {
						result = "已换货完成,请勿重覆换货";
					} else {
						int update = jdbcTemplate.update("update ec_service_order_main set order_status='90' where service_id='"
								+ serviceId + "'");
						if (update == 0) {
							result = "换货单号：" + serviceId + ",换货失败";
						} else {
							result = "换货单号：" + serviceId + ",换货成功";
						}
					}
				}
			}
		} catch (Exception e) {
			result = "换货单号：" + serviceId + ",换货失败";
			logger.info("exception:{}", e.toString());
		}
		return "changeJson";
	}

	// 商品已送達(同步)
	void deliveryOrder(String orderId) {
		int updateOrder = jdbcTemplate
				.update("update ec_order_main set is_sync='1', sync_date=sysdate -2 ,order_st='35' where order_id='" + orderId
						+ "'");
		int updateOP = jdbcTemplate
				.update("update ec_order_product set logistic_send_dt=sysdate,logistic_final_dt=sysdate, logistic_st='40',logistic_company='SE',logistic_ref_num='9009970513' where order_id='"
						+ orderId + "'");
	}

	// 商品已送達(for帳戶餘額&禮品卡付清專用)
	// void deliveryOrderForCashEqZero(String orderId) {
	// int updateOP = jdbcTemplate
	// .update("update ec_order_product set logistic_send_dt=sysdate,logistic_final_dt=sysdate, logistic_st='40',logistic_company='SE',logistic_ref_num='9009970513' where order_id='"
	// + orderId + "'");
	// }

	// 已收款(出货处理中)，部份取消用
	void syncOrder(Orders order) {
		String[] orderIds = order.getJoinOrders().split(",");
		for (String oid : orderIds) {
			if (!oid.equals(order.getOrderId())) {
				order = orderService.get(oid);
			}
			order.setOrderSt("25");
			batchJobService.save(Orders.ORDER_BEAN.CREATE.getValue(), toXML(order), null, order.getOrderId());
			order.setSync(true);
			// 訂單同步時，若是付款方式COD／POS，需要寫入payment_dt
			if (order.getPaymentTp().equals(Orders.ORDER_PAYMENT_TYPE.ARRIVE.getValue())
					|| order.getPaymentTp().equals(Orders.ORDER_PAYMENT_TYPE.ARRIVE_CARD.getValue())) {
				order.setPaymentDt(new Date());
			}
			baseMgr.update(order);
		}
	}

	String toXML(Orders order) {
		String xml = null;
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			BeanWriter beanWriter = new BeanWriter(baos);
			beanWriter.enablePrettyPrint();
			beanWriter.write(order);
			xml = baos.toString();
			beanWriter.flush();
			baos.flush();
			beanWriter.close();
			baos.close();
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		return xml;

	}

	public String getOrderId() {
		return orderId;
	}

	public void setOrderId(String orderId) {
		this.orderId = orderId;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}

	public String getServiceId() {
		return serviceId;
	}

	public void setServiceId(String serviceId) {
		this.serviceId = serviceId;
	}
}
